import { CSS } from '@dnd-kit/utilities';
import React, { useState, useRef } from 'react';
import type { DropdownProps } from 'antd/es/dropdown';
import { DndContext, DragEndEvent } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import type { TableProps, ColumnType } from 'antd/es/table';
import { Dropdown, Modal, message, type MenuProps } from 'antd';
import { DragOutlined, ExportOutlined } from '@ant-design/icons';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';

// 定义右键菜单项
export type ContextMenuKey = 'sort-asc' | 'sort-desc' | 'hide-column' | 'reset' | 'set-columns' | 'export-data';

// 扩展的列类型
export interface CustomColumnType<RecordType> extends ColumnType<RecordType> {
    customData?: any;
    key: string; // 确保有 key 属性
}

// 高阶组件 props
interface WithHeaderContextMenuProps<RecordType> {
    onMenuClick?: (key: ContextMenuKey, column: CustomColumnType<RecordType>) => void;
    menuItems?: MenuProps['items'];
    dropdownProps?: DropdownProps;
    getNewCols?: (newCols: CustomColumnType<RecordType>[]) => void;
}

// 可排序的列项组件
const SortableItem: React.FC<{ id: string; children: React.ReactNode }> = ({ id, children }) => {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id });

    const style: React.CSSProperties = {
        padding: '8px 16px',
        marginBottom: '8px',
        backgroundColor: '#fff',
        border: '1px solid #f0f0f0',
        borderRadius: '4px',
        cursor: 'move',
        display: 'flex',
        alignItems: 'center',
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
    };

    return (
        <div ref={setNodeRef} style={style} {...attributes} {...listeners} >
            <DragOutlined style={{ marginRight: '8px' }} />
            {children}
        </div>
    );
};

// 高阶组件函数
const withHeaderContextMenu = <RecordType extends object = any>({
    onMenuClick,
    menuItems,
    dropdownProps,
    getNewCols
}: WithHeaderContextMenuProps<RecordType> = {}) => {
    return (WrappedTable: React.ComponentType<TableProps<RecordType>>) => {
        const EnhancedTable: React.FC<TableProps<RecordType>> = ({ columns: originalColumns, ...props }) => {
            const [menuVisible, setMenuVisible] = useState(false);
            const [modalVisible, setModalVisible] = useState(false);
            const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
            const [currentHeader, setCurrentHeader] = useState<CustomColumnType<RecordType> | null>(null);
            const [tempColumns, setTempColumns] = useState<CustomColumnType<RecordType>[]>([]);
            const tableRef = useRef<HTMLDivElement>(null);

            // 初始化时确保 columns 有 key
            const columns = originalColumns?.map((col, index) => {
                // 判断是否为列组
                if ('children' in col && Array.isArray(col.children)) {
                    return {
                        ...col,
                        key: col.key || `col-group-${index}`,
                    };
                }
                return {
                    ...col,
                    key: col.key || (col as ColumnType<RecordType>).dataIndex?.toString() || `col-${index}`,
                };
            }) as CustomColumnType<RecordType>[];

            const handleHeaderContextMenu = (
                event: React.MouseEvent<HTMLDivElement>,
                column: CustomColumnType<RecordType>
            ) => {
                event.preventDefault();
                setCurrentHeader(column);
                setMenuPosition({
                    x: event.clientX,
                    y: event.clientY,
                });
                setMenuVisible(true);
            };

            const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
                if (currentHeader && onMenuClick) {
                    onMenuClick(key as ContextMenuKey, currentHeader);
                }

                if (key === 'set-columns') {
                    setTempColumns([...columns]);
                    setModalVisible(true);
                }

                setMenuVisible(false);
            };

            const handleCloseMenu = () => {
                setMenuVisible(false);
            };

            // 默认菜单项
            const defaultMenuItems: MenuProps['items'] = [
                { key: 'sort-asc', label: '升序排序' },
                { key: 'sort-desc', label: '降序排序' },
                { key: 'hide-column', label: '隐藏列' },
                { key: 'reset', label: '重置列' },
                { key: 'export-data', label: '导出' },
                { key: 'set-columns', label: '列设置', icon: <ExportOutlined /> },
            ];

            const menu = {
                onClick: handleMenuClick,
                items: menuItems || defaultMenuItems
            }

            // 处理拖拽结束
            const handleDragEnd = ({ active, over }: DragEndEvent) => {
                if (over && active.id !== over.id) {
                    setTempColumns((prev) => {
                        const oldIndex = prev.findIndex((col) => col.key === active.id);
                        const newIndex = prev.findIndex((col) => col.key === over.id);
                        return arrayMove(prev, oldIndex, newIndex);
                    });
                }
            };

            // 应用列排序
            const applyColumnOrder = () => {
                // 这里可以添加实际应用列排序的逻辑
                message.success('列顺序已更新');
                getNewCols?.(tempColumns);
                setModalVisible(false);
            };

            // 增强列配置
            const enhancedColumns = columns?.map((col) => ({
                ...col,
                title: (
                    <div onContextMenu={(e) => handleHeaderContextMenu(e, col)}>
                        {
                            typeof col.title === 'function'
                                ? col.title({ ...col.customData, title: col.title })
                                : col.title
                        }
                    </div>
                ),
            })) as ColumnType<RecordType>[];

            return (
                <div ref={tableRef}>
                    <WrappedTable columns={enhancedColumns} {...props} />

                    <Dropdown
                        menu={menu}
                        open={menuVisible}
                        onOpenChange={handleCloseMenu}
                        {...dropdownProps}
                    >
                        <div
                            style={{
                                position: 'fixed',
                                left: menuPosition.x,
                                top: menuPosition.y,
                                width: '1px',
                                height: '1px',
                            }}
                        />
                    </Dropdown>

                    {/* 导出列设置的 Modal */}
                    <Modal
                        title="列设置"
                        open={modalVisible}
                        onOk={applyColumnOrder}
                        onCancel={() => setModalVisible(false)}
                        width={600}
                    >
                        <div style={{ marginBottom: '16px' }}>
                            <p>拖拽调整列顺序，点击确定应用更改</p>
                        </div>

                        <DndContext
                            modifiers={[restrictToVerticalAxis]}
                            onDragEnd={handleDragEnd}
                        >
                            <SortableContext
                                items={tempColumns.map((col) => col.key)}
                                strategy={verticalListSortingStrategy}
                            >
                                {tempColumns.map((column) => (
                                    <SortableItem key={column.key} id={column.key}>
                                        {column.title as React.ReactNode}
                                    </SortableItem>
                                ))}
                            </SortableContext>
                        </DndContext>
                    </Modal>
                </div>
            );
        };

        return EnhancedTable;
    };
};

export default withHeaderContextMenu;